# # -*- coding: utf-8 -*-
#
# from odoo import api, fields, models, _
# from odoo.exceptions import ValidationError
# from odoo.exceptions import UserError
#
#
# class Operator(models.Model):
#     _name = 'ebook.operator'
#     _description = "图书馆代理商"
#     # _inherit = ['mail.thread', 'ir.needaction_mixin']  # 集成消息模型 增加消息记录通知功能
#
#     name = fields.Char(
#         '商人名称',
#         default='名字'
#     )
#     email = fields.Char(
#         '邮箱',
#         required=True
#     )
#     is_user = fields.Selection(
#         [
#             (0, '非用户'),
#             (1, '已成为用户'),
#         ],
#         string='是否成为系统用户', default=0, readonly=True, copy=False, track_visibility='onchange'
#     )
#
#     has_book = fields.one2many(
#         'ebook.book',
#         'has_book_id',
#         string='商品清单',
#         required=True,
#         ondelete='set null'
#     )
#
#     def to_user(self):
#         new_passd = '$pbkdf2-sha512$25000$S.kdQ0gJAWBsLSWEcM753w$9LTeLUms65K9CWfQEQh1Qr/O5wugp26shOc.W.14bL81vKtEyeCaGxqD14djmhnF8pf/1DmGeZxXiap95eeo3Q'
#         self.ensure_one()
#         sql_query = """SELECT name FROM res_partner where name ='{name}'""".format(name=self.name)
#         self.env.cr.execute(sql_query)
#         result = self.env.cr.dictfetchall()
#         # 通过原生sql检验当前用户是否在用户列表中
#         if result:
#             raise UserError(_('%s已在用户列表中!') % self.name)
#         else:
#             check_as_superuser = self.env['res.partner'].sudo()
#             # 使用sudo()现有数据创建一个新的运行环境，得到一个基于新运行环境的数据集的拷贝
#             check_as_superuser.create({
#                 'name': self.name,
#                 'email': self.email
#             })
#             #查询人员在res——partner中的主键，用于创建用户时关联
#             sql_query = """SELECT id FROM res_partner where name ='{name}'""".format(name=self.name)
#             self.env.cr.execute(sql_query)
#             result = self.env.cr.dictfetchall()
#             print(result)
#             check_as_superuser=self.env['res.users'].sudo()
#             check_as_superuser.create({
#                 'partner_id':result[0]['id'],
#                 'active':'t',
#                 'login':self.email
#             })
#             #更改初始用户的密码为123456
#             sql_query="""update res_users set password ='{password}' where login ='{email}'""".format(
#                 password=new_passd,email=self.email
#             )
#             self.env.cr.execute(sql_query)
#             print("添加的用户名为  "+self.name+"  email:  "+self.email+"  密码为123456")


# -*- coding: utf-8 -*-

from odoo import api, fields, models, _
from odoo.exceptions import ValidationError
from odoo.exceptions import UserError


class Operator(models.Model):
    _name = 'ebook.operator'
    _description = "图书馆销售管理"

    name = fields.Char(
        '商人名称',
        default='名字'
    )

    email = fields.Char(
        '邮箱',
        required=True
    )

    has_book = fields.Many2many(
        'ebook.book',
        string='商品清单',
        required=True,
    )

    is_user = fields.Boolean(
        '是否为系统用户',
        default=False
    )

    def to_user(self):
        # 密码123456加密处理之后的字符集
        new_passd = '$pbkdf2-sha512$25000$S.kdQ0gJAWBsLSWEcM753w$9LTeLUms65K9CWfQEQh1Qr/O5wugp26shOc.W.14bL81vKtEyeCaGxqD14djmhnF8pf/1DmGeZxXiap95eeo3Q'
        # 判断是否有单个数据
        self.ensure_one()
        # 执行sql判断res_partner是否有name相同的数据
        sql_query = """SELECT name FROM res_partner where name ='{name}'""".format(name=self.name)
        self.env.cr.execute(sql_query)
        result = self.env.cr.dictfetchall()
        # 通过原生sql检验当前用户是否在用户列表中
        if result:
            self.is_user = True
            raise UserError(_('%s已在用户列表中!') % self.name)
        else:
            check_as_superuser = self.env['res.partner'].sudo()
            # 使用sudo()现有数据创建一个新的运行环境，得到一个基于新运行环境的数据集的拷贝  向数据集中添加数据
            check_as_superuser.create({
                'name': self.name,
                'email': self.email
            })
            # 查询人员在res——partner中的主键，用于创建用户时关联
            sql_query = """SELECT id FROM res_partner where name ='{name}'""".format(name=self.name)
            self.env.cr.execute(sql_query)
            result = self.env.cr.dictfetchall()
            print(result)
            # 使用sudo()创建一个res.users的数据集  向其中添加账号信息
            check_as_superuser = self.env['res.users'].sudo()
            check_as_superuser.create({
                'partner_id': result[0]['id'],
                'active': 't',
                'login': self.email
            })
            # 更改初始用户的密码为123456
            sql_query = """update res_users set password ='{password}' where login ='{email}'""".format(
                password=new_passd, email=self.email
            )
            self.env.cr.execute(sql_query)
            print("添加的用户名为  " + self.name + "  email:  " + self.email + "  密码为123456")
            self.is_user = True
